import React, { useEffect, useRef, useState } from 'react'
import styles from './index.less'
import { Empty, Popconfirm, Modal, message, Breadcrumb, Table, Space, Popover, Button, Pagination, Input, Form, Select, Badge } from 'antd';
import { CommentModelState, useDispatch, useSelector, useStore } from 'umi';
import timeChange from '../../time/index'
import CommonFooter from '@/components/commonFooter';
const { TextArea } = Input;
export default function Comment() {
  const { commentDelet, commentList, commentListlength, commentAdopt,commentreply } = useSelector(
    (state: { comment: CommentModelState }) => state.comment,
  );

  const dispatch = useDispatch();
  const [page, setPage] = useState()
  const [flag, setFlag] = useState(false);
  const [name, setName] = useState('')
  const [email, setemail] = useState('')
  const [status, setStatus] = useState('')
  const [isvisible, setIsvisible] = useState(false)
  const [value, setValues] = useState('')
  //获取数据 搜索功能
  useEffect(() => {
    dispatch({
      //  命名空间/请求接口的方法
      type: 'comment/getcommentList',
      payload: {
        page,
        name,
        email,
        status
      }
    });
  }, [page, name, email, status, commentDelet, commentAdopt,commentreply]);
  //通过
  function adopt(e: any) {
    const user = JSON.parse(localStorage.getItem("user") as string)
    if (user.role === "admin") {
      dispatch({
        type: "comment/getCommentAdopt",
        payload: {
          id: e.id,
          pass: true
        }
      })
      dispatch({
        //  命名空间/请求接口的方法
        type: 'comment/getcommentList',
        payload: {
          page,
          name,
          email,
          status
        }
      });
      message.success("评论已通过")
    } else {
      message.error("访客无权经行操作")
    }
  }
  //拒绝
  function refuse(e: any) {
    const user = JSON.parse(localStorage.getItem("user") as string)
    if (user.role === "admin") {
      dispatch({
        type: "comment/getCommentAdopt",
        payload: {
          id: e.id,
          pass: false
        }
      })
      dispatch({
        //  命名空间/请求接口的方法
        type: 'comment/getcommentList',
        payload: {
          page,
          name,
          email,
          status
        }
      });
      message.success("评论已拒绝")
    } else {
      message.error("访客无权经行操作")
    }
  }

  //评论回复
  function showModal() {
    // 打开弹窗
    setIsvisible(true)
  }
  // 获取回复内容
  function values(e: any) {
    setValues(e.target.value)
  }
  //回复
  function hideOk(e: any) {
    const user = JSON.parse(localStorage.getItem("user") as string)
    if (user.role === "admin") {
      let obj = {
        content: value,
        email: e.email,
        hostId: e.id,
        html: e.html,
        name:e.name,
        parentCommentId: e.hostId,
        pass: false,
        replyUserEmail: e.replyUserEmail,
        replyUserName: e.name,
        url: `/article/${e.hostId}`,
        userAgent: e.userAgent,
      }
      dispatch({
        type: "comment/getCommentreply",
        payload: obj
      })
      setIsvisible(false)
      message.success("回复成功")
    } else {
      message.error("用户权限不足")
    }
    setValues('')
  }
  // 关闭弹窗
  function hideModal() {
    setIsvisible(false)

  }
  //数据头部
  const columns = [
    {
      title: `状态`,
      dataIndex: 'state',
      width: 40,
      key: "state"
    },
    {
      title: '称呼',
      dataIndex: 'name',
      width: 70,
      key: 'name'
    },
    {
      title: '联系方式',
      dataIndex: 'email',
      width: 70,
      key: 'email'
    },
    {
      title: '原始内容',
      dataIndex: 'contents',
      width: 70,
      key: "contents"
    },
    {
      title: 'HTML内容',
      dataIndex: 'htmlContent',
      width: 70,
      key: 'htmlContent'
    },
    {
      title: '管理文章',
      dataIndex: 'articles',
      width: 50,
      key: 'articles'
    },
    {
      title: '创建时间',
      dataIndex: 'times',
      width: 70,
      key: 'times'
    },
    {
      title: '父级评论',
      dataIndex: 'nothing',
      width: 40,
      key: 'nothing'
    },
    {
      title: '操作',
      
      key: 'operation',
      width: 90,
      render: (e: any) => <Space>
        <a onClick={() => { adopt(e.operation) }}>通过</a>
        <a onClick={() => { refuse(e.operation) }}>拒绝</a>
        <a onClick={showModal}>回复</a>
        <Modal
          okText="回复"
          cancelText="取消"
          title="回复评论" visible={isvisible}
          onCancel={hideModal}
          onOk={() => hideOk(e.operation)}
          maskStyle={{ background: "rgba(0,0,0,0.1)" }}
        >
          <TextArea onChange={(e) => values(e)} rows={4} placeholder="请输入评论内容 (支持 MarKdown)" value={value} style={{ height: "154.9667px", minHeight: "94.9667px", maxHeight: "178.967px", overflowY: "hidden", resize: "none", background: "var(--bg-second)" }} />
        </Modal>
        <Popconfirm title="确定要删除吗?"
          onConfirm={() => { confirm(e.operation) }}
          okText="确认"
          cancelText="取消"
        >
          <a>删除</a>
        </Popconfirm>
      </Space>,
    },
  ];
  //删除
  function confirm(e: any) {
    const user = JSON.parse(localStorage.getItem("user") as string)
    if (user.role === 'admin') {
      dispatch({
        type: 'comment/getCommentDelet',
        payload: e.id
      })
      dispatch({
        //  命名空间/请求接口的方法
        type: 'comment/getcommentList',
        payload: {
          page,
          name,
          email,
          status
        }
      });
      message.success("评论已删除")
    } else {
      message.error("访客无权经行操作")
    }

  }

  const data = [];
  for (let i = 0; i < commentList.length; i++) {
    data.push({
      key:commentList[i]['id'],
      state: commentList[i]['pass'] == true ? <span><Badge status="success" />通过</span> : <span><Badge status="warning" />未通过</span>,//状态
      name: commentList[i]['name'],//称呼
      email: commentList[i]['email'],//联系方式
      contents: <Popover title='评论详情-原始能容' content={commentList[i]['content']}><a>查看内容</a></Popover>,//原始内容
      htmlContent: <Popover title='评论详情-HTML能容' content={commentList[i]['html']}><a>查看内容</a></Popover>,//HTML内容
      articles: <Popover placement="right" title='页面预览'
        content={<iframe src="http://localhost:8000/Login" ></iframe>}>
        <a className={styles.article} href='http://localhost:8000/Login'>文章</a>
      </Popover>,
      times: <span>{timeChange(commentList[i]['createAt'])}</span>,  //文章
      nothing: <span>无</span>,//父级评论
      operation: commentList[i],//操作
    });
  }
  // 设置多选框
  const [selectedRowKeys, changeSelectedRowKeys] = useState([])
  // 改变多选框
  function onSelectChange(selectedRowKeys: any, selectedRows: any) {
    changeSelectedRowKeys(selectedRowKeys)
    selectedRows.length ? setFlag(true) : setFlag(false);
  };
  // 将单选框赋值
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  //获取搜索参数
  const onFinish = (values: any) => {
    if (values.name) {
      setName(values.name);
    } else {
      setName('');
    }
    if (values.email) {
      setemail(values.email);
    } else {
      setemail('');
    }
    if (values.status) {
      setStatus(values.status == 'publish' ? '1' : '0')
    } else {
      setStatus('')
    }
  };
  //重置
  const [form] = Form.useForm();
  const onReset = () => {
    form.resetFields();
  };
  //选择框通过
  function adoptCheckbox(){
    const user = JSON.parse(localStorage.getItem("user") as string)
    if (user.role === 'admin') {
      selectedRowKeys.forEach(item=>{
        dispatch({
          type: "comment/getCommentAdopt",
          payload: {
            id: item,
            pass: true
          }
        })
      })
      dispatch({
        //  命名空间/请求接口的方法
        type: 'comment/getcommentList',
        payload: {
          page,
          name,
          email,
          status
        }
      });
      message.success("评论已通过")
    }else{
      message.error("访客无权经行操作")
    }
  }
  //选择框拒绝
  function refuseCheckbox(){
    const user = JSON.parse(localStorage.getItem("user") as string)
    if (user.role === 'admin') {
      selectedRowKeys.forEach(item=>{
        dispatch({
          type: "comment/getCommentAdopt",
          payload: {
            id: item,
            pass: false
          }
        })
      })
      dispatch({
        //  命名空间/请求接口的方法
        type: 'comment/getcommentList',
        payload: {
          page,
          name,
          email,
          status
        }
      });
      message.success("评论已拒绝")
    }else{
      message.error("访客无权经行操作")
    }
  }
  //选择框删除
  function deleteCheckbox(){
    const user = JSON.parse(localStorage.getItem("user") as string)
    if (user.role === 'admin') {
      selectedRowKeys.forEach(item=>{
        dispatch({
          type: 'comment/getCommentDelet',
          payload: item
        })
      })
      dispatch({
        //  命名空间/请求接口的方法
        type: 'comment/getcommentList',
        payload: {
          page,
          name,
          email,
          status
        }
      });
      message.success("评论已删除")
    } else {
      message.error("访客无权经行操作")
    }
  }
  return (
    <div className={styles.box}>
      <div className={styles.comment_head} >
        <Breadcrumb>
          <Breadcrumb.Item>
            <a href="/">工作台</a>
          </Breadcrumb.Item>
          <Breadcrumb.Item>
            <a href="">评论管理</a>
          </Breadcrumb.Item>
        </Breadcrumb>
      </div>
      <div className={styles.comment}>

        <div className={styles.comment_search}>
          <div className={styles.inp}>
            <Form
              form={form}
              name="control-hooks"
              onFinish={onFinish}
              className={styles.comment_form}
            >
              <div className={styles.comment_screen}>
                <Form.Item
                  name="name"
                  label="名称"
                  className={styles.comment_from_item}
                >
                  <Input placeholder="请输入页面名称" />
                </Form.Item>
                <Form.Item
                  name="email"
                  label="Email"
                  className={styles.comment_from_item}
                >
                  <Input placeholder="请输入页面路径" />
                </Form.Item>
                <Form.Item
                  label="状态"
                  name="status"
                  className={styles.comment_from_item}
                >
                  <Select>
                    <Select.Option value="publish">已通过</Select.Option>
                    <Select.Option value="draft">未通过</Select.Option>
                  </Select>
                </Form.Item>
              </div>
              <div className={styles.comment_operation}>
                <Button
                  type="primary"
                  htmlType="submit"
                  className={styles.comment_button_search}
                >
                  搜索
                </Button>

                <Button
                  htmlType="button"
                  onClick={onReset}
                  className={styles.comment_button_reset}
                >
                  重置
                </Button>
              </div>
            </Form>
          </div>
        </div>
        <div className={styles.comment_conten}>
          <div className={styles.space_button} style={flag ? { opacity: '1' } : { opacity: '0' }}>
            <Space>
              <Button onClick={adoptCheckbox}>通过</Button>
              <Button onClick={refuseCheckbox}>拒绝</Button>
              <Button danger onClick={deleteCheckbox}>删除</Button>
            </Space>
          </div>
          {
            commentList.length > 0 ?
              <div>
                <Table

                  columns={columns}
                  dataSource={data}
                  scroll={{ x: 1500, y: 350 }}
                  pagination={false}
                  rowSelection={rowSelection}
                />

                <div className={styles.page}>
                  <Pagination defaultCurrent={1}
                    total={commentListlength}
                    defaultPageSize={12}
                    pageSizeOptions={[8, 12, 24, 36]}
                    onChange={(current: any) => {
                      setPage(current)
                    }}
                  />
                </div>

              </div>
              : <Empty imageStyle={{
                height: 220,
                marginBottom: -80,
              }} image={Empty.PRESENTED_IMAGE_SIMPLE} description='暂无数据' />
          }
        </div>
      </div>
      <div className={styles.foor}>
        <CommonFooter></CommonFooter>
      </div>
    </div>

  )
}
